<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdvertPageList, deleteAdvert } from '@/api/advert/admin'
import { getAdvertPositionPageList } from '@/api/advertPosition/admin'
import { ContentWrap } from '@/components/ContentWrap'
import type { AdvertItem, AdvertPositionOption } from '@/api/advert/types'

// 搜索表单
const searchForm = reactive({
  positionId: undefined,
  name: '',
  startTime: '',
  endTime: ''
})

// 广告位选项
const advertPositionOptions = ref<AdvertPositionOption[]>([])

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 列表数据
const advertList = ref<AdvertItem[]>([])
const loading = ref(false)

// 获取广告位选项
const fetchAdvertPositionOptions = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100
    }
    const response = await getAdvertPositionPageList(params)
    if (response.code === 200) {
      advertPositionOptions.value = response.data.list.map(item => ({
        id: item.id,
        name: item.name
      }))
    } else {
      ElMessage.error(response.message || '获取广告位列表失败')
    }
  } catch (error) {
    ElMessage.error('获取广告位列表失败')
  }
}

// 获取列表数据
const fetchAdvertList = async () => {
  try {
    loading.value = true
    const params = {
      positionId: searchForm.positionId,
      name: searchForm.name,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime,
      pageNum: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    }

    const response = await getAdvertPageList(params)
    if (response.code === 200) {
      advertList.value = response.data.list
      pagination.value.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取广告列表失败')
    }
  } catch (error) {
    ElMessage.error('获取广告列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchAdvertList()
}

// 重置搜索条件
const handleReset = () => {
  searchForm.positionId = undefined
  searchForm.name = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
  pagination.value.currentPage = 1
  fetchAdvertList()
}

// 删除广告
const deleteAdvertHandle = (row: AdvertItem) => {
  ElMessageBox.confirm(`确定要删除广告"${row.name}"吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteAdvert(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchAdvertList()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  fetchAdvertList()
}

const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val
  fetchAdvertList()
}

// 路由跳转
const router = useRouter()

// 跳转到创建页面
const jumpToCreatePage = () => {
  router.push({ name: 'AdvertCreate' })
}

// 跳转到详情页面
const jumpToDetailPage = (row: AdvertItem) => {
  router.push({ name: 'AdvertDetail', params: { id: row.id } })
}

// 跳转到编辑页面
const jumpToEditPage = (row: AdvertItem) => {
  router.push({ name: 'AdvertEdit', params: { id: row.id } })
}

// 初始化
onMounted(() => {
  fetchAdvertPositionOptions()
  fetchAdvertList()
})
</script>

<template>
  <ContentWrap title="广告列表" message="展示广告主要信息等">
    <!-- 搜索表单 -->
    <div>
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="广告位">
          <el-select
            v-model="searchForm.positionId"
            placeholder="请选择广告位"
            style="width: 200px"
            clearable
          >
            <el-option
              v-for="item in advertPositionOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="广告名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入广告名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 200px"
          />
          <span class="date-separator">-</span>
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="jumpToCreatePage">新增广告</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表 -->
    <el-table :data="advertList" style="width: 100%" v-loading="loading" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="广告名称" />
      <el-table-column prop="positionId" label="广告位ID" />
      <el-table-column prop="sort" label="排序" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="180" />
      <el-table-column prop="endTime" label="结束时间" width="180" />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <div class="button-container">
            <el-button size="small" type="info" @click="jumpToDetailPage(scope.row)">
              查看
            </el-button>
            <el-button size="small" type="primary" @click="jumpToEditPage(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteAdvertHandle(scope.row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />
  </ContentWrap>
</template>

<style scoped>
.date-separator {
  margin: 0 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.button-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}
.button-container :deep(.el-button) {
  margin: 0;
}
</style>